package com.talent.web.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

/**
 * @ClassName：Demo
 * @Author: hszhou
 * @Date: 2024/11/8 16:03
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
public class SignatureUtil {

    private static final String ALGORITHM = "SHA-256";
    private static final String SECRET_KEY="talent";



    public static  String generateSignature(Map<String,String> params) throws NoSuchAlgorithmException {

        TreeMap<String,String> sortedParams = new TreeMap<>(params);
        StringBuilder sb = new StringBuilder();

        sortedParams.forEach((k,v)->sb.append(k).append("=").append(v).append("&"));
        sb.append("secret_key=").append(SECRET_KEY);

        MessageDigest instance = MessageDigest.getInstance(ALGORITHM);
        byte[] digest = instance.digest(sb.toString().getBytes(StandardCharsets.UTF_8));

        StringBuilder hexString = new StringBuilder();

        for (byte b : digest) {
            String hex = Integer.toHexString(0xff & b);
            if(hex.length()==1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();

    }

    public static boolean verifySignature(Map<String,String> params,String signature) throws NoSuchAlgorithmException {
        String s = generateSignature(params);
        return s.equals(signature);
    }
}
